package com.xiaomei.manager.web.controller;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

import com.xiaomei.manager.dao.PositionMapper;
import com.xiaomei.manager.model.UserAndRecommandDto;

import org.apache.log4j.Logger;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;


import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.xiaomei.manager.model.Banner;
import com.xiaomei.manager.model.Broadcast;
import com.xiaomei.manager.model.Complain;
import com.xiaomei.manager.model.Experience;
import com.xiaomei.manager.model.Position;
import com.xiaomei.manager.model.User;
import com.xiaomei.manager.service.IPositionService;
import com.xiaomei.manager.service.IUserService;
import com.xiaomei.manager.utils.BirthdayConverterUtils;
import com.xiaomei.manager.utils.CodeUtils;
import com.xiaomei.manager.utils.Constants;
import com.xiaomei.manager.utils.OSSClientUtils;
import com.xiaomei.manager.web.aliyun.OSS.AliyunUpload;
import com.xiaomei.manager.web.dto.UserAndDriverAuthDto;
import com.xiaomei.manager.web.dto.req.UserQueryDto;
import com.xiaomei.manager.web.page.Page;


@Controller
@RequestMapping("/appuser")
public class AppUserController {

	@Autowired
	private IPositionService IPositionService;
	@Autowired
	private  IUserService iUserService;
	private Logger logger = Logger.getLogger(AppUserController.class);
    @RequiresPermissions(value="appuser:view")
    @RequestMapping()
    public String list(HttpServletRequest request,UserQueryDto dto,Page<UserAndDriverAuthDto> page){
		if(page.getPageSize()>50) {
			page.setPageSize(50);
		}
    	iUserService.getselectList(dto, page);
    	request.setAttribute("dto", dto);
		if(page.getTotalRecord()>50) {
			page.setTotalRecord(50);
		}
    	request.setAttribute("page", page);
    	return "appuser/list";
   }
    
    @RequiresPermissions("appuser:update")
	@RequestMapping(value = "/{id}/update",method = RequestMethod.GET)
	public String detail(@PathVariable("id") Integer id, Model model){
		User selectByPrimaryKey = (User)iUserService.selectByPrimaryKey(id);
		model.addAttribute("User",selectByPrimaryKey);
		 model.addAttribute("op", "提交");
		return "/appuser/edit";
	}
    @RequiresPermissions("appuser:update")
    @RequestMapping(value = "/{id}/update", method = RequestMethod.POST)
    public String update(User User, @RequestParam("files") MultipartFile[] files , @PathVariable("id") Integer id, RedirectAttributes redirectAttributes, HttpServletRequest request){	    		    
    	if(files != null && files.length > 0){  
            //循环获取file数组中得文件  
    		int i ;
            for(i = 0;i<files.length;i++){  
                MultipartFile file = files[i];	                
                String fileName = file.getOriginalFilename();	                
                if(file != null && file.getSize() > 0 && fileName != null && !fileName.equals("")){	       	
	 	            String extention = fileName.substring(fileName.lastIndexOf("."), fileName.length());	                         
	                String finalFileName = "appuser/"+id+"/img_"+(i+1)+extention;
	                String url = AliyunUpload.getOSSUrl(Constants.OSS_BUCKET_COMMON, finalFileName);
	                if(i == 0){
	                	User.setImg1(url);
	                }else if(i == 1){
	                	User.setImg2(url);
	                }else if(i == 2){
	                	User.setImg3(url);
	                }else if(i == 3){
	                	User.setImg4(url);
	                }else if(i == 4){
	                	User.setImg5(url);
	                }else if(i == 5){
	                	User.setImg6(url);
	                }
	            try{
	                AliyunUpload.getInstance();	                
	                AliyunUpload.uploadMultipartFile(finalFileName, Constants.OSS_BUCKET_COMMON, file);
	                }catch (Exception e) {
						logger.info("修改banner失败！");
					}	                  
                }  
            } 
    	}
    	//banner backban = iBannerService.selectbannerById(id);
    	//ban.setVersion(backban.getVersion());
    	iUserService.updateByPrimaryKeySelective(User);
        redirectAttributes.addFlashAttribute("msg", "修改成功");
        return "redirect:/appuser";
    }
	@RequiresPermissions("appuser:update")
	@RequestMapping(value = "/{userCode}",method = RequestMethod.GET)
	public String detail(@PathVariable("userCode") String userCode, Model model){
		User selectByPrimaryKey = (User)iUserService.selectByUserCode(userCode);
		model.addAttribute("User",selectByPrimaryKey);
		return "/appuser/edit";
	}

	@RequiresPermissions("appuser:update")
	@RequestMapping(value = "/recommand")
	public String RecommendList(HttpServletRequest request, UserQueryDto dto, Page<UserAndRecommandDto> page){
		iUserService.getUserRecommandValue(dto, page);
		request.setAttribute("dto", dto);
		request.setAttribute("page", page);
		return "/appuser/recommandMgr";
	}

	@RequiresPermissions("appuser:update")
	@RequestMapping(value = "/updateRecommend")
	@ResponseBody
	public String detail(String userCode, Integer value){
		iUserService.updateUserRecommend(userCode, value);
		return "Success";
	}
	
	@RequiresPermissions("appuser:create")
	@RequestMapping( value = "/create",method = RequestMethod.GET)
	public String initAddForm(Model model) {
		model.addAttribute("appuser", new User());
        model.addAttribute("op", "新增");
        return "appuser/add";
	}
    
	@RequiresPermissions("appuser:create")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public String create(User appuser, @RequestParam("files") MultipartFile[] files , RedirectAttributes redirectAttributes) {
		String generateUserCode = CodeUtils.generateUserCode();
		Random random = new Random();
		List<Position> selectAll = IPositionService.selectAll();
		Position position = selectAll.get(random.nextInt(selectAll.size()));
		Position p=new Position();
		p.setUserCode(generateUserCode);
		p.setLat(position.getLat());
		p.setLng(position.getLng());
		p.setPositionPoint(position.getPositionPoint());
		User user1= new User();
		StringBuffer sb = new StringBuffer();
		// 上传图片
		if(files != null && files.length > 0 && files[0].getSize() > 0) {
			long millis = System.currentTimeMillis() / 1000;
			for(int i=0; i<files.length; i++) {
				MultipartFile file = files[i];
				
				try {
					BufferedImage buff = ImageIO.read(file.getInputStream());
					int width = buff.getWidth();
					int height = buff.getHeight();
					
					String suffix = OSSClientUtils.getSuffixByFilename(file.getOriginalFilename());
					String filename = "appuser/" + millis + "/img" + (i + 1) + "_" + width + "X" + height + "." + suffix;

					if(AliyunUpload.uploadMultipartFile(filename, Constants.OSS_BUCKET_COMMON, file)) {
						String url = AliyunUpload.getOSSUrl(Constants.OSS_BUCKET_COMMON, filename);
						sb.append(url);
					}
					
				} catch (IOException e) {
					e.printStackTrace();
				}
				if(i+1 < files.length) {
					sb.append(",");
				}
			}
		}
		String birthday = appuser.getBirthday();
		if(birthday != null && !"".equals(birthday)) {
			String[] birthdays = BirthdayConverterUtils.splitBirthday(birthday);
			// 设置用户年龄
			Integer age = BirthdayConverterUtils.getAge(Integer.valueOf(birthdays[0]));
			user1.setAge(age);
			// 设置用户星座
			String constellation = BirthdayConverterUtils.getConstellation(Integer.valueOf(birthdays[1]), Integer.valueOf(birthdays[2]));
			user1.setHoroscope(constellation);
		}	
		String[] split = sb.toString().split(",");
		user1.setImg1(split[0]);
		user1.setImg2(split[1]);
		user1.setDisplayPic(split[1]);
		user1.setMobile(appuser.getMobile());
		user1.setUserCode(generateUserCode);
		user1.setBirthday(birthday);
		user1.setNickname(appuser.getNickname());
		user1.setSex(appuser.getSex());
		IPositionService.insertSelective(p);
		iUserService.insertUser(user1);
        redirectAttributes.addFlashAttribute("msg", "新增成功");
        return "redirect:/appuser";
    }
}
